package com.jk.controller;

import com.jk.constant.LoginConstant;
import com.jk.constant.RegisterConstant;
import com.jk.po.ClentPO;
import com.jk.service.ClientLoginService;
import com.jk.utils.CheckImgUtil;
import com.jk.vo.ClentVo;
import com.jk.vo.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/***
 * @ClassName: ClientLoginController
 * @Description:TODO 客户登陆 注册
 * @Auther: TaiBai
 * @Date: 2021/6/30 9:17
 * @version : V1.0
 */
@RestController
@RequestMapping("clent")
@Api(tags= "客户登陆注册接口")
public class ClientLoginController  {
    //日志记录对象
    private static Logger logger = LoggerFactory.getLogger(ClientLoginController.class);
    @Autowired
    private ClientLoginService clientLoginService;
    @Autowired
    private RedisTemplate redisTemplate;
    //发送者的邮箱账号
    @Value("${spring.mail.username}")
    private String mailusername;
    @Autowired
    JavaMailSender jms;

    /*
    * @Author  TaiBai
    * @Description //TODO 客户账号密码登陆
    * @Date 14:40 2021/6/30
    * @method  loginClient
    * @Param [clentVo]
    * @return com.jk.vo.ResultInfo
    **/
    @PostMapping("loginClient")
    @ApiOperation(value = "客户登陆")
    public @ResponseBody
    ResultInfo loginClient(@RequestBody ClentVo clentVo, HttpSession session){

        //返回前台对象
        ResultInfo resultInfo = new ResultInfo();
        ClentPO clentPO = new ClentPO();
        BeanUtils.copyProperties(clentVo,clentPO);
        //session中取到验证码

        /*String checkcode = (String) session.getAttribute("checkcode");
        //判断验证码
        if (!(clentVo.getCode()).equals(checkcode)) {
            resultInfo.setMessage("验证码错误");
            logger.info("登陆失败,验证码错误");
        } else {*/
        if (clentVo.getCusnumber() == null || clentVo.getCusnumber().equals("")){
            resultInfo.setMessage("请输入您的账号密码!");
            return resultInfo;
        }

            try {
                //查询数据库客户信息
                ClentPO resultClent = clientLoginService.queryClientByName(clentPO.getCusnumber());
                if (resultClent == null){
                    resultInfo.setMessage("账号不存在");
                    resultInfo.setStatus(LoginConstant.LOGIN_STATUS_FAIL_ACCENT);
                    logger.info("登陆失败 账号不存在");
                }
                else{
                    if (!resultClent.getCuspassword().equals(clentVo.getCuspassword())) {
                        resultInfo.setMessage("密码错误");
                        resultInfo.setStatus(LoginConstant.LOGIN_STATUS_FAIL_ACCENT);
                        logger.info("登陆失败 密码错误");
                    } else {
                        resultInfo.setMessage("登陆成功");
                        resultInfo.setCode(200);
                        resultInfo.setData(resultClent);
                        resultInfo.setStatus(LoginConstant. LOGIN_STATUS_SUCCESS);
                        logger.info("登陆成功");
                        //存session
                        session.setAttribute("clent",resultClent);
                    }
                }
            }catch (Exception e){
                logger.error("登陆请求失败:"+e.getMessage());
                resultInfo.setCode(404);
                resultInfo.setMessage("服务器异常,请重试");
            }
        //}
        return resultInfo;
    }
    /*
    * @Author  TaiBai
    * @Description //TODO 手机号登陆
    * @Date 20:28 2021/7/5
    * @method  phoneLoginClient
    * @Param [clentVo]
    * @return com.jk.vo.ResultInfo
    **/
    @PostMapping("phoneLoginClient")
    @ApiOperation(value = "手机号登陆",produces = "application/json")
    public @ResponseBody ResultInfo phoneLoginClient(@RequestBody ClentVo clentVo,HttpSession session){
        //返回前台对象
        ResultInfo resultInfo = new ResultInfo();
        ClentPO clentPO = new ClentPO();
        BeanUtils.copyProperties(clentVo,clentPO);

        if (clentVo.getCusphone() == null || clentVo.getCusphone().equals("")){
            resultInfo.setMessage("请输入您注册的手机号,获取验证码");
            return resultInfo;
        } else if (clentVo.getPhonecode() == null || clentVo.getPhonecode().equals("")){
            resultInfo.setMessage("请输入验证码!!");
            return resultInfo;
        }
        try {
            //取出redis的验证码
            String code = (String) redisTemplate.opsForValue().get(clentVo.getCusphone());
            if (!code.equals(clentVo.getPhonecode())){
                resultInfo.setMessage("验证码输入错误");
                resultInfo.setStatus(LoginConstant.LOGIN_STATUS_FAIL_PASSWORD);
                logger.info("登陆失败 手机验证码错误");
            }else {
                //查询数据库手机号
                ClentPO resultClent = clientLoginService.queryClientByPhone(clentPO.getCusphone());
                resultInfo.setMessage("登陆成功");
                resultInfo.setCode(200);
                resultInfo.setData(resultClent);
                resultInfo.setStatus(LoginConstant. LOGIN_STATUS_SUCCESS);
                logger.info("登陆成功");
                //存session
                session.setAttribute("clent",resultClent);
            }
        }catch (Exception e){
            resultInfo.setMessage("服务器异常,请重试!");
            resultInfo.setCode(400);
        }
        return resultInfo;
    }






    /*
    * @Author  TaiBai
    * @Description //TODO 用户注册
    * @Date 9:45 2021/7/1
    * @method  registerClient
    * @Param [clentPO]
    * @return com.jk.vo.ResultInfo
    **/
    @PostMapping("registerClient")
    @ApiOperation(value = "用户注册",produces = "application/json")
    public @ResponseBody ResultInfo registerClient(@RequestBody ClentVo clentVO) {
        //返回前台对象
        ResultInfo resultInfo = new ResultInfo();
        ClentPO clentPO = new ClentPO();
        BeanUtils.copyProperties(clentVO,clentPO);
        if (clentVO == null || clentVO.getCusnumber() == null || clentVO.getCuspassword().equals("") || clentVO.getCusphone().equals("") || clentVO.getCusemail().equals("")){
            resultInfo.setMessage("请规范填写注册信息!");
            return resultInfo;
        }
            try {
                //根据账号查询数据库是否有该账号
                ClentPO result = clientLoginService.queryClientByName(clentPO.getCusnumber());

                if (result != null &&  result.getCusnumber() != null){
                    resultInfo.setMessage("该账号已被注册,请重新输入!");
                    return resultInfo;
                }
                //根据手机号查询数据库是否有手机号
                ClentPO resultClent = clientLoginService.queryClientByPhone(clentPO.getCusphone());
                if (resultClent != null && resultClent.getCusphone() != null ){
                    resultInfo.setMessage("该手机号已被注册,请重新输入!");
                    return resultInfo;
                }
                    try {
                        clentPO.setCuspicture(RegisterConstant.REGISTER_DEFULT_HEAD);//默认头像
                        clentPO.setRegtime(new DateTime().toString());//系统当前时间
                        clentPO.setCusname("用户202107096971");
                        //注册信息新增至数据库
                        clientLoginService.saveClient(clentPO);
                        //建立邮件消息
                        SimpleMailMessage mainMessage = new SimpleMailMessage();
                        //发送者邮箱
                        mainMessage.setFrom(mailusername);
                        //接收者邮箱
                        mainMessage.setTo(clentPO.getCusemail());
                        //发送的邮件标题
                        mainMessage.setSubject(RegisterConstant.MAIL_TITLE);
                        //发送的内容
                        mainMessage.setText(RegisterConstant.MAIL_CONTENT+"账号"+clentPO.getCusnumber()+",密码"+clentPO.getCuspassword()+".");
                        //发送
                        jms.send(mainMessage);
                        resultInfo.setCode(200);
                        resultInfo.setMessage("注册成功,请注意查收邮件!");
                        logger.info("客户注册成功");
                    }catch (Exception e){
                        clientLoginService.saveClient(clentPO);
                        //建立邮件消息
                        SimpleMailMessage mainMessage = new SimpleMailMessage();
                        //发送者邮箱
                        mainMessage.setFrom(mailusername);
                        //接收者邮箱
                        mainMessage.setTo(clentPO.getCusemail());
                        //发送的邮件标题
                        mainMessage.setSubject(RegisterConstant.MAIL_TITLE);
                        //发送的内容
                        mainMessage.setText(RegisterConstant.MAIL_CONTENT+"账号"+clentPO.getCusnumber()+",密码"+clentPO.getCuspassword()+".");
                        //发送
                        jms.send(mainMessage);
                        logger.error("注册新增或发送邮件失败:"+e.getMessage());
                        //resultInfo.setCode(500);
                        //resultInfo.setMessage("接口调用异常");
                        resultInfo.setCode(200);
                        resultInfo.setMessage("注册成功,请注意查收邮件!");
                    }
                    return resultInfo;
        }catch (Exception e){
                logger.error("注册请求失败:"+e.getMessage());
                resultInfo.setCode(404);
                resultInfo.setMessage("服务器异常,请重试!");
                return resultInfo;
        }

    }

    /*
    * @Author  TaiBai
    * @Description //TODO 获取图片验证码拿到session
    * @Date 10:15 2021/7/3
    * @method  imgCode
    * @Param [request, response]
    * @return void
    **/
    @RequestMapping("imgCode")
    @ResponseBody
    @ApiOperation(value = "获取验证码")
    public void imgCode(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        CheckImgUtil.buildCheckImg(request, response,session);
    }
    /*
    * @Author  TaiBai
    * @Description //TODO 获取登陆状态
    * @Date 17:27 2021/7/7
    * @method  loggedIn
    * @Param []
    * @return com.jk.vo.ResultInfo
    **/
    @PostMapping("loggedIn")
    @ApiOperation(value = "获取登陆状态")
    public @ResponseBody ResultInfo loggedIn(HttpServletRequest request){
        ResultInfo resultInfo = new ResultInfo();
        try {
            ClentPO clent = (ClentPO) request.getSession().getAttribute("clent");
            resultInfo.setMessage("获取登陆状态成功");
            logger.info("获取登陆状态成功");
            resultInfo.setCode(200);
            resultInfo.setData(clent);
        }catch (Exception e){
            resultInfo.setMessage("获取登陆状态失败");
            resultInfo.setCode(400);
            logger.error("获取登陆状态失败");
        }
        return resultInfo;
    }












}
